/*
 * @Description:
 * @Author: minghuiXiao
 * @Date: 2021-06-30 15:48:59
 * @LastEditTime: 2024-07-30 16:02:11
 * @LastEditors: rodchen rodchen_king@outlook.com
 */
import React, { useEffect, useRef, useState } from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { Button, Switch, message, Popover } from 'antd';
import BsBasicSulaQueryTable from '@/components/businessComponent/BsSulaQueryTable';
import { handleCommonTimeRender } from '@/common/businessType';
import CopyWrapper from '@/components/CopyWrapper';
import { request } from 'xtepbssula';
import ModalFormMoudle from '@/components/BasicComponent/ModalFormMoudle';
import { label_status } from '@/common/menu';
import { authFn, getDictionarySource, getDictionaryTextByValue } from '@/utils/utils';
import ColorContent from './Children/index';

export default (props: any) => {
  const forwardedRef: any = useRef(null);
  const modalRef: any = useRef(null);
  const [modalStatus, setModalStatus]: any = useState({});
  const [open, setOpen] = useState(false);

  const remoteDataSource = {
    url: '/oms-ops/tag',
    method: 'GET',
    convertParams: {
      type: 'bs-tableConvertParamsType',
      initialValues: {
        sorter: 'desc-id',
      },
    },
    converter: 'bs-tableConvertType',
  };
  const config = {
    remoteDataSource,
    rowSelection: {},
    actionsRender: [
      {
        type: 'button',
        props: {
          type: 'primary',
          children: '新增',
        },
        code: 'OMS_Channel_LabelList_add',
        action: () => {
          setModalStatus({ title: '标签新建', mode: 'create' });
          modalRef?.current?.modalOpen();
        },
      },
      {
        type: 'button',
        props: {
          type: 'primary',
          children: '启用',
        },
        code: 'OMS_Channel_LabelList_enableDisable_Batch',
        funcProps: {
          disabled: (ctx: any) => {
            const selectedRows = ctx.table.getSelectedRows() || [];
            return (
              !selectedRows.length ||
              (selectedRows as any[]).some((item) => item.status === 1)
            );
          },
        },
        action: [
          {
            url: '/oms-ops/tag/batchModifyStatus',
            method: 'patch',
            convertParams: (ctx: any) => ({
              tagIds: ctx.table
                .getSelectedRows()
                .map((item: any) => item.code)
                .join(','),
              status: 1,
            }),
            successMessage: '修改状态成功',
          },
          'refreshTable',
        ],
      },
      {
        type: 'button',
        props: {
          type: 'danger',
          children: '禁用',
        },
        code: 'OMS_Channel_LabelList_Disable_Batch',
        funcProps: {
          disabled: (ctx: any) => {
            const selectedRows = ctx.table.getSelectedRows() || [];
            return (
              !selectedRows.length ||
              (selectedRows as any[]).some((item) => item.status === 0)
            );
          },
        },
        action: [
          {
            url: '/oms-ops/tag/batchModifyStatus',
            method: 'patch',
            convertParams: (ctx: any) => ({
              tagIds: ctx.table
                .getSelectedRows()
                .map((item: any) => item.code)
                .join(','),
              status: 0,
            }),
            successMessage: '修改状态成功',
          },
          'refreshTable',
        ],
      },
      {
        type: 'button',
        props: {
          type: 'danger',
          children: '删除',
        },
        code: 'OMS_Channel_LabelList_Delete_Batch',
        funcProps: {
          disabled: (ctx: any) => {
            const selectedRows = ctx.table.getSelectedRows() || [];
            return (
              !selectedRows.length ||
              (selectedRows as any[]).some((item) => item.status === 1)
            );
          },
        },
        action: [
          { type: 'bs-modalConfirm', content: '确定删除？' },
          {
            url: (ctx: any) =>
              `/oms-ops/tag/${ctx.table
                .getSelectedRows()
                .map((item: { id: string;[key: string]: any }) => item.id)
                .join(',')}`,
            method: 'delete',
          },
          'refreshTable',
        ],
      },
    ],
    fields: [
      {
        name: 'qp-code-like',
        label: '标签编码',
        field: {
          type: 'input',
          props: {
            placeholder: '请输入',
            allowClear: true,
            maxLength: 32,
          },
        },
      },
      {
        name: 'qp-name-like',
        label: '标签名称',
        field: {
          type: 'input',
          props: {
            placeholder: '请输入',
            allowClear: true,
            maxLength: 32,
          },
        },
      },
      {
        name: 'qp-systemFlag-eq',
        label: '是否系统标签',
        field: {
          type: 'select',
        },
        initialSource: [
          { text: '否', value: 0 },
          { text: '是', value: 1 },
        ],
      },
      {
        name: 'qp-tagType-eq',
        label: '标签类型',
        field: {
          type: 'select',
          props: {
            placeholder: '请选择',
          },
        },
        initialSource: getDictionarySource('order_tag_type'),
      },
      {
        name: 'qp-tagGroupCode-eq',
        label: '业务类型',
        field: {
          type: 'select',
          props: {
            placeholder: '请选择',
          },
        },
        initialSource: getDictionarySource('tag_group_code'),
      },
      {
        name: 'qp-status-eq',
        label: '状态',
        field: {
          type: 'select',
          props: {
            allowClear: true,
          },
        },
        initialSource: label_status.rows(),
      },
      {
        name: 'qp-modifyUserId-eq',
        label: '修改人',
        field: {
          type: 'bs-searchSelect',
          props: {
            requestConfig: {
              url: `/user/employee/pageList?withAccount=true`,
              filter: 'qp-name-like',
              mappingTextField: 'name',
              mappingValueField: 'accountId',
            },
          },
        },
      },
      {
        name: 'qp-modifyTime-ge*fullDate*qp-modifyTime-le',
        label: '修改时间',
        field: {
          type: 'rangepicker',
          props: {
            allowClear: true,
          },
        },
      },
    ],
    columns: [
      {
        key: 'code',
        title: '标签编码',
        tableHeadFilterKey: 'qp-code-like',
        render: ({ text, record }: any) => (
          <CopyWrapper text={text}>
            <Button
              type="link"
              disabled={!authFn('OMS_Channel_LabelList_view')}
              onClick={() => {
                setModalStatus({ title: '标签查看', mode: 'view', record });
                modalRef?.current?.modalOpen();
              }}
            >
              {text}
            </Button>
          </CopyWrapper>
        ),
      },
      {
        key: 'name',
        title: '标签名称',
        tableHeadFilterKey: 'qp-name-like',
      },
      {
        key: 'systemFlag',
        title: '是否系统标签',
        tableHeadFilterKey: '是否系统标签',
        render: ({ text }: { text: number }) => ({ 0: '否', 1: '是' }[text]),
      },
      {
        key: 'tagType',
        title: '标签类型',
        tableHeadFilterKey: 'qp-tagType-eq',
        render: ({ text }) => getDictionaryTextByValue('order_tag_type', text)
      },
      {
        key: 'detail',
        title: '标签备注',
        ellipsis: true,
      },
      {
        key: 'tagGroupCode',
        title: '业务类型',
        tableHeadFilterKey: 'qp-tagGroupCode-eq',
        render: ({ text }) => getDictionaryTextByValue('tag_group_code', text)
      },
      {
        key: 'status',
        title: '状态',
        render: ({ text, record }: any) => {
          return (
            <Switch
              checked={text == 1}
              disabled={text == 0 ? !authFn('OMS_Channel_LabelList_enableDisable'): !authFn('OMS_Channel_LabelList_Disable')}
              onChange={(checked: boolean) => {
                // 调用接口 调整状态启禁用 然后刷新页面
                request({
                  url: `/oms-ops/tag/modifyStatus/${record.id}/${+checked}`,
                  method: 'PATCH',
                }).then(() => {
                  message.success(checked ? '启用成功' : '禁用成功');
                  forwardedRef.current?.tableRef?.current?.refreshTable();
                });
              }}
            />
          );
        },
      },
      {
        key: 'modifyUserName',
        title: '修改人',
      },
      {
        key: 'modifyTime',
        title: '修改时间',
        sorter: true,
        render: ({ text }: any) => handleCommonTimeRender(text),
      },
      {
        key: 'operaction',
        title: '操作',
        // isPermissionColumn: true,
        render: [
          {
            type: 'link',
            props: {
              children: '编辑',
            },
            visible: '#{record.status===0}',
            code: 'OMS_Channel_LabelList_edit',
            action: [
              ({ history, record }: any) => {
                console.log('@弹窗');
                setModalStatus({ title: '标签编辑', mode: 'edit', record });
                modalRef?.current?.modalOpen();
              },
            ],
          },
          // {
          //   type: 'link',
          //   props: {
          //     children: '删除',
          //     style: {
          //       color: 'red',
          //     },
          //   },
          //   code: 'OMS_Channel_LabelList_delete',
          //   confirm: '确认删除当前项吗？',
          //   // 禁用时可以删除
          //   visible: '#{record.status == 0}',
          //   action: [
          //     {
          //       url: `/oms-ops/tag/#{record.id}`,
          //       method: 'DELETE',
          //       successMessage: '删除成功',
          //     },
          //     'refreshtable',
          //   ],
          // },
        ],
      },
    ],
    rowKey: 'id',
  };

  const modalFormMoudleProps = {
    modalProps: {
      title: modalStatus.title,
      onOk: async () => {
        const res = await modalRef.current.formRef.current.validateFields();
        let url = '/oms-ops/tag',
          method = 'POST',
          params = { ...res };
        if (modalStatus.mode === 'edit') {
          url = `/oms-ops/tag/${modalStatus.record.id}`;
          method = 'PATCH';
        }
        return request({
          url,
          method,
          params,
          converter: () => {
            message.success('提交成功');
            forwardedRef.current?.tableRef?.current?.refreshTable();
            modalRef?.current?.modalOpen(false);
          },
        });
      },
    },
    formProps: {
      mode: modalStatus?.mode,
      remoteValues: {
        url: `/oms-ops/tag/${modalStatus?.record?.id}`,
        converter: (ctx: any) => {
          console.log(`🚀 => ctx:`, ctx);
          return ctx.data;
        },
      },
      initialValues: { systemFlag: 0, keyFlag: 1, isManualDelete: 0 },
      fields: [
        {
          name: 'code',
          label: '标签编码',
          field: {
            type: 'input',
          },
          rules: [{ required: true }],
          initialVisible: modalStatus?.mode !== 'create',
          initialDisabled: true,
        },
        {
          name: 'name',
          label: '标签名称',
          field: {
            type: 'input',
            props: {
              placeholder: '请输入',
              allowClear: true,
              disabled: modalStatus?.record?.systemFlag == 1,
            },
          },
          rules: [{ required: true }],
        },
        {
          name: 'systemFlag',
          label: '是否系统标签',
          field: {
            type: 'select',
            props: {
              allowClear: true,
            },
          },
          initialSource: [
            { text: '否', value: 0 },
            { text: '是', value: 1 },
          ],
          initialDisabled: true,
          rules: [{ required: true }],
        },
        {
          name: 'tagType',
          label: '标签类型',
          field: {
            type: 'select',
            props: {
              allowClear: true,
              disabled: modalStatus?.record?.systemFlag == 1,
            },
          },
          initialSource: getDictionarySource('order_tag_type', true),
          rules: [{ required: true }],
        },
        {
          name: 'tagGroupCode',
          label: '业务类型',
          field: {
            type: 'select',
            props: {
              allowClear: true,
              disabled: modalStatus?.record?.systemFlag == 1,
            },
          },
          initialSource: getDictionarySource('tag_group_code'),
          rules: [{ required: true }],
        },
        {
          name: 'detail',
          label: '标签备注',
          field: {
            type: 'input',
            props: {
              maxLength: 30,
            },
          },
        },
        {
          name: 'keyFlag',
          label: '是否重点标签',
          field: {
            type: 'select',
            props: {
              allowClear: true,
            },
          },
          initialSource: [
            { text: '否', value: 0 },
            { text: '是', value: 1 },
          ],
          rules: [{ required: true }],
        },
        {
          name: 'isManualDelete',
          label: '是否可以手工删除',
          field: {
            type: 'select',
            props: {
              allowClear: true,
            },
          },
          initialSource: [
            { text: '否', value: 0 },
            { text: '是', value: 1 },
          ],
          rules: [{ required: true }],
        },
        {
          name: 'colour',
          label: '标签颜色',
          field: (ctx) => {
            const color = ctx.form.getFieldValue('colour');
            const onSelectColor = (color) => {
              ctx.form.setFieldValue('colour', color);
              setOpen(false);
            }
            return (
              <Popover open={open} content={<ColorContent onSelectColor={onSelectColor} />} title="选择颜色" trigger="click" placement="bottom" >
                {color ? (
                  <div style={{
                    width: '24px',
                    height: '24px',
                    borderRadius: '4px',
                    background: color,
                  }}
                    onClick={() => setOpen(!open)}>
                  </div>
                ) : <div style={{
                  color: '#00A94E',
                  cursor: 'pointer'
                }}
                  onClick={() => setOpen(!open)}>点击选择标签颜色</div>}
              </Popover>
            )
          },
          rules: [{ required: true }],
        },
      ],
    },
  };

  return (
    <PageHeaderWrapper>
      <BsBasicSulaQueryTable {...config} forwardedRef={forwardedRef} />
      <ModalFormMoudle {...modalFormMoudleProps} ref={modalRef} />
    </PageHeaderWrapper>
  );
};
